//输入某二叉树的前序遍历和中序遍历的结果，请构建该二叉树并返回其根节点。 
//
// 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 
//
// 
//
// 示例 1: 
//
// 
//Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
//Output: [3,9,20,null,null,15,7]
// 
//
// 示例 2: 
//
// 
//Input: preorder = [-1], inorder = [-1]
//Output: [-1]
// 
//
// 
//
// 限制： 
//
// 0 <= 节点个数 <= 5000 
//
// 
//
// 注意：本题与主站 105 题重复：https://leetcode-cn.com/problems/construct-binary-tree-from-
//preorder-and-inorder-traversal/ 
// Related Topics 树 数组 哈希表 分治 二叉树 👍 811 👎 0

package leetcode.editor.cn;
//leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution07 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildZiTree(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
    }

    //左闭右闭
    //注意：preRight-PreLeft == inRigth - inLeft,因为一棵树的前序和中序遍历长度是一样的
    private TreeNode buildZiTree(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
        if(preRight - preLeft < 0){ //数组为空的情况
            return null;
        }
        if(preRight - preLeft == 0){ //只有一个节点
            return new TreeNode(preorder[preLeft]);
        }

        int rootValue = preorder[preLeft];
        TreeNode root = new TreeNode(rootValue);

        int delimiterIndex = 0;
        for(int i = inLeft; i <= inRight; i++){
            if(inorder[i] == rootValue){
                delimiterIndex = i;
            }
        }

        root.left = buildZiTree(preorder, inorder, preLeft+1,preLeft+delimiterIndex-inLeft,
                                    inLeft, delimiterIndex-1);
        root.right = buildZiTree(preorder, inorder, preLeft+delimiterIndex-inLeft+1,preRight,
                                    delimiterIndex+1,inRight);

        return root;
    }

    public static void main(String[] args) {
        new Solution07().buildTree(new int[]{1,2},new int[]{2,1});
    }
}
//leetcode submit region end(Prohibit modification and deletion)
